# users/services.py
from django.core.mail import send_mail
from django.conf import settings
import uuid
import threading


def async_send_verification_code(pending_user, verification_code):
    # 使用线程执行发送邮件的函数
    thread = threading.Thread(target=send_verification_code, args=(pending_user, verification_code))
    thread.start()


# 用于在注册视图中为pending_user发送验证码
def send_verification_code(pending_user, verification_code):
    subject = 'Your Verification Code for Account Activation'
    from_email = f"LetzAlgo <{settings.EMAIL_HOST_USER}>"
    recipient_list = [pending_user.email]

    # 构建邮件的文本内容
    message = f"""
    Dear {pending_user.username},

    Your verification code is: {verification_code}

    Please enter this code to activate your account.

    Thank you for using our service.

    Best regards,
    LetzAlgo Team
    """

    try:
        # 发送纯文本邮件
        send_mail(
            subject=subject,
            message=message,
            from_email=None,  # 可以省略或设置为 None，Django 会使用 DEFAULT_FROM_EMAIL
            recipient_list=recipient_list,
            fail_silently=False,
        )
        print(f"Verification code sent to {pending_user.email}")
    except Exception as e:
        print(f"Failed to send verification email to {pending_user.email}: {e}")


def avatar_upload_path(instance, filename):
    # 使用 `instance.user.id // 100` 生成文件夹，使用 UUID 生成文件名
    return f'avatars/{instance.user.id // 100}/{uuid.uuid4().hex}.jpg'